package com.sjp.myspring.web.servlet;

import com.sjp.myspring.annotation.JPRequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

public class JPHandlerAdapter {
    boolean supports(Object handler) {
        return true;
    }

    JPModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        JPHandlerMapping handlerMapping = (JPHandlerMapping) handler;
        Object obj = handlerMapping.getController();
        Method method = handlerMapping.getMethod();
        Parameter[] parameters = method.getParameters();

        //方法参数
        Object[] params = new Object[parameters.length];
        //request 参数
        Map<String, String[]> parameterMap = request.getParameterMap();

        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            if (parameter.getType() == HttpServletRequest.class) {
                params[i] = request;
            } else if (parameter.getType() == HttpServletResponse.class) {
                params[i] = response;
            } else if (parameter.isAnnotationPresent(JPRequestParam.class)) {
                JPRequestParam requestParam = parameter.getAnnotation(JPRequestParam.class);
                String name = requestParam.name();
                if (parameterMap.containsKey(name)) {
                    params[i] = convertType(parameter.getType(), parameterMap.get(name));
                }
            }
        }

        try {
            Object result = method.invoke(obj, params);
            if (result instanceof JPModelAndView) {
                return (JPModelAndView) result;
            } else {
                //result做为数据返回
                return new JPModelAndView();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //500
            return new JPModelAndView();
        }

    }

    private Object convertType(Class<?> type, String[] values) {
        if (values == null) {
            return null;
        }
        if (type == Integer.class) {
            return Integer.valueOf(values[0]);
        }
        if (type == Double.class) {
            return Double.valueOf(values[0]);
        }
        return values;
    }


}
